<template>
  <div class="about">
    <el-card class="box-cardAdd">
      <div style="text-align: left">
        <a  style="color: #409EFF;vertical-align: 5px;" class="el-icon-edit">
          组卷配置</a>
        <i class="el-icon-arrow-right"></i>
        <a  style="color: #409EFF;vertical-align: 5px;pointer-events:none" class="el-icon-lock">
          考试权限</a>
        <i class="el-icon-arrow-right"></i>
        <a  style="color: #409EFF;vertical-align: 5px;pointer-events:none" class="el-icon-setting">
          补充配置</a>
      </div>
    </el-card>
    <div style="text-align: left;margin: 10px 0">
      <el-button type="primary" style="float: right" @click="submitForm('examAddNew')">提交</el-button>
      <el-button @click="goBack()">上一步</el-button>
    </div>
    <div>
      <el-card>
        <el-card style="margin: 0 auto;margin-top: 20px;width: 720px">
          <h1 style="font-size: 18px">添加考试模式</h1>
          <el-form :model="examAddNew" :rules="rules" ref="examAddNew" label-width="120px" class="demo-ruleForm" style="text-align: left;margin: 10px 0">
            <el-form-item label="考试名称" prop="examName" style="width: 500px">
              <el-input v-model="examAddNew.examName"></el-input>
            </el-form-item>
            <el-form-item label="考试描述" prop="examDesc" style="width: 500px">
              <el-input v-model="examAddNew.examDesc"></el-input>
            </el-form-item>
            <el-form-item label="总分" prop="totalScore">
              <el-input-number v-model="examAddNew.totalScore"  label="总分" :disabled="true"></el-input-number>
            </el-form-item>
            <el-form-item label="及格分数" prop="passScore">
              <el-input-number v-model="examAddNew.passScore" :max="examAddNew.totalScore" label="及格分"  :precision="0"
                               :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="考试时常(分)" prop="duration">
              <el-input-number v-model="examAddNew.duration" :max="240" label="考试时常" :precision="0"
                               :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="考试开始时间">
              <el-date-picker
                  v-model="examAddNew.starTimeStr"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="考试结束时间">
              <el-date-picker
                  v-model="examAddNew.endTimeStr"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="请选择专业" prop="majorId">
              <el-select v-model="examAddNew.majorId" :value="examAddNew.majorId" placeholder="专业" style="width: 150px" @change="getClassArr">
                <el-option v-for="item in majorArr" :label="item.majorName" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择班级" prop="classId">
              <el-select
                  v-model="classValue"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="班级" style="width: 150px">
                <el-option v-for="item in classArr" :label="item.className" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </el-card>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      questions:[],
      startDataTime:'',
      endDataTime:'',
      redios:'2',
      examAddNew:{
        examName:'',
       examDesc:'',
        type:'',
       password:'',
        //考试时间
        duration:'',
        //开始时间
        starTimeStr:'',
        endTimeStr:'',
        //总分
        totalScore:60,
        //及格线
        passScore:'',

        majorId:'',
        majorName:'',

       classIds:'',

        classNames:'',

        questions:[]
      },
      majorArr:[],
      classArr:[],
      classValue:[],
      rules: {
        examName: [
          { required: true, message: '请输入考试名称', trigger: 'blur' }
        ],
        examDesc: [
          { required: true, message: '请输入考试介绍', trigger: 'blur' }
        ],
        date1: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'blur' }
        ],
        totalScore: [
          { required: true, message: '您缺少总分', trigger: 'blur' }
        ],
        passScore: [
          { required: true, message: '请输入及格分数', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入考试时常', trigger: 'blur' }
        ],
        majorId:[
          { required: true, message: '请输入专业id', trigger: 'blur' }
        ]
      }
    }
  },
  methods:{
    goBack() {
      this.$router.push('/exam/addNew2')
    },
    goNext() {
      this.examAddNew.type = this.redios;
    },
    LoadExamAddNew(){
      let examAddNew = localStorage.getItem("examAddNew");
      examAddNew = JSON.parse(examAddNew);
      this.examAddNew = examAddNew;
      console.log(this.examAddNew)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.classValue)
          //验证失败会反复拼接数据
          this.examAddNew.classIds = "";
          this.examAddNew.classNames = "";
          //将选中的数组拼接成字符串
          for (let i = 0; i < this.classArr.length; i++) {
            for (let j = 0; j <this.classValue.length; j++) {
              if(this.classValue[j]==this.classArr[i].id){
                this.examAddNew.classIds += this.classValue[j]+",";
                this.examAddNew.classNames +=this.classArr[i].className+",";
                continue;
              }
            }
          }
          //去除拼接的,
          this.examAddNew.classIds = this.examAddNew.classIds.substring(0,this.examAddNew.classIds.length-1);
          this.examAddNew.classNames = this.examAddNew.classNames.substring(0,this.examAddNew.classNames.length-1);

          //传递专业名称
          for (let i = 0; i < this.majorArr.length; i++) {
            if(this.examAddNew.majorId==this.majorArr[i].id){
              this.examAddNew.majorName = this.majorArr[i].majorName;
              break;
            }
          }


          //将时间对象存储出来
          let url = "http://localhost:9283/exam/add-new";
          let jwt = localStorage.getItem("localJwt");
          //更换questions对象
          let questions = [];
          for (let i = 0; i < this.examAddNew.questions.length; i++) {
            console.log(this.examAddNew.questions[i].id);
            console.log(this.examAddNew.questions[i].level);
            let q = {
              questionId:this.examAddNew.questions[i].id,
              scores:this.examAddNew.questions[i].level*1
            }
            questions.push(q);
          }
          this.examAddNew.questions = questions;
          console.log(this.examAddNew);
          this.axios
              .create({
                'headers':{
                  'Authorization':jwt
                }
              })
              .post(url,this.examAddNew).then((response)=>{
            let jsonResult = response.data;
            if(jsonResult.state==20000){
              this.classArr = jsonResult.data;
              localStorage.removeItem("questions");
              localStorage.removeItem("examAddNew");
              this.$router.push('/exam')
              if (jsonResult.jwt!=null){
                localStorage.setItem("localJwt",jsonResult.jwt);
              }
            }else if(jsonResult.state==70100){
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
              this.$router.push('/')
            } else{
              this.$alert(response.data.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getMajorArr(){
      let url = "http://localhost:9281/major/list";
      let jwt = localStorage.getItem("localJwt");
      console.log(url);
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          })
          .get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.majorArr = jsonResult.data;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else{
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },

    getClassArr(){
      this.examAddNew.classId = '';
      this.examAddNew.className='';
      let url = "http://localhost:9281/class/list?id="+this.examAddNew.majorId;
      console.log(url);
      this.axios.get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.classArr = jsonResult.data;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else{
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
          });
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.LoadExamAddNew();
    this.getMajorArr();
  }
}
</script>
<style>
.box-cardAdd .el-card__body{
  padding: 0;
}
.box-cardAdd .el-card__body a{
  text-decoration: none;
  cursor:pointer;
  margin:0 140px;
  vertical-align: 5px;
  font-size: 14px;
  font-weight: bold;
}
.box-cardAdd .el-card__body i{
  text-decoration: none;
  cursor:pointer;
  margin:0 140px;
  font-size: 14px;
  font-weight: bold;
}
.box-cardAdd .el-card__body i{
  font-size: 32px;
  padding: 0;
  margin:0;
  color: #8492a6
}
</style>
